package com.tdcy.sys.util.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.tdcy.sys.service.bean.LoginInfoBean;

/**
 * 
 * All rights Reserved, Designed By www.eastcom.com
 * 
 * @title: UserUtils.java
 * @package com.eastcom.modules.sys.utils
 * @description: 用户工具类
 *
 */
@SuppressWarnings("unchecked")
public class ShiroUtils {

	/**
	 * 获取当前用户
	 * 
	 * @return 取不到返回 new User()
	 */
	public static LoginInfoBean getUserInfo() {
		ShiroUser principal = getPrincipal();
		if (principal != null) {
			LoginInfoBean user = principal.getLoginInfo();
			if (user != null) {
				return user;
			}
			return new LoginInfoBean();
		}
		// 如果没有登录，则返回实例化空的User对象。
		return new LoginInfoBean();
	}

	/**
	 * 获取授权主要对象
	 */
	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	/**
	 * 获取当前登录者对象
	 */
	public static ShiroUser getPrincipal() {
		try {
			Subject subject = SecurityUtils.getSubject();
			ShiroUser principal = (ShiroUser) subject.getPrincipal();
			if (principal != null) {
				return principal;
			}
			// subject.logout();
		} catch (UnavailableSecurityManagerException e) {

		} catch (InvalidSessionException e) {

		}
		return null;
	}

	public static Session getSession() {
		try {
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null) {
				session = subject.getSession();
			}
			if (session != null) {
				return session;
			}
			// subject.logout();
		} catch (InvalidSessionException e) {

		}
		return null;
	}

}
